package com.major.tree.binarytree;

public class Node {
    private int no;
    private String name;
    private Node leftNode;
    private Node rightNode;

    @Override
    public String toString() {
        return "Node{" +
                "no=" + no +
                ", name='" + name + '\'' +
                '}';
    }

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Node getLeftNode() {
        return leftNode;
    }

    public void setLeftNode(Node leftNode) {
        this.leftNode = leftNode;
    }

    public Node getRightNode() {
        return rightNode;
    }

    public void setRightNode(Node rightNode) {
        this.rightNode = rightNode;
    }

    public Node(int no, String name) {
        this.no = no;
        this.name = name;
    }

    public Node() {
    }

    // 中序遍历
    public void inoOrder() {
        if (leftNode != null) {
            leftNode.inoOrder();
        }
        System.out.println(this.toString());
        if (rightNode != null) {
            rightNode.inoOrder();
        }
    }

    // 查询
    public Node getNodeByNo(int no) {
        Node resNode = null;

        if (leftNode != null) {
            resNode = leftNode.getNodeByNo(no);
        }
        if (resNode != null) {
            return resNode;
        }
        if (this.no == no) {
            return this;       // 只返回了这一个值
        }
        if (this.rightNode != null) {
            resNode = this.rightNode.getNodeByNo(no);
        }
        return resNode;
    }

    // 删除
    public void deleteByNo(int no) {
        if (leftNode != null && leftNode.no == no) {
            leftNode = null;
            return;
        }
        if (leftNode != null) {
            leftNode.deleteByNo(no);
        }

        if (rightNode != null && rightNode.no == no) {
            rightNode = null;
            return;
        }
        if (rightNode != null){
            rightNode.deleteByNo(no);
        }

    }
}
